// pages/blog-edit/blog-edit.js
const MAX_WORDS_NUM = 140;
const MAX_IMG_NUM = 9;
const db = wx.cloud.database();
let content = ''; //当前输入内容
let userInfo = {}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    wordNum: 0,
    footerBottom: 0,
    images: [],
    selectPhoto: true, //
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    userInfo = options;
    console.log(options, "adasdsd")
  },

  onInput(event) {
    let wordNum = event.detail.value.length;
    if (wordNum >= MAX_WORDS_NUM) {
      wordNum = `最大字数为${MAX_WORDS_NUM}`
    }
    this.setData({
      wordNum
    })
    content = event.detail.value;
  },
  // 获取焦点
  onFocus(event) {
    this.setData({
      footerBottom: event.detail.height
    })
  },
  // 失去焦点
  onBlur() {
    this.setData({
      footerBottom: 0
    })
  },

  onChooseImage() {
    let max = MAX_IMG_NUM - this.data.images.length;
    wx.chooseImage({
      count: max,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],

      success: (res) => {
        this.setData({
          images: this.data.images.concat(res.tempFilePaths)
        })
        max = MAX_IMG_NUM - this.data.images.length;
        this.setData({
          selectPhoto: max <= 0 ? false : true
        })
        console.log(max, "this is res")
      }
    })
  },

  onDelImg(event) {
    const index = event.target.dataset.index;
    this.data.images.splice(index, 1)
    this.setData({
      images: this.data.images
    })
    if (this.data.images.length == MAX_IMG_NUM - 1) {
      this.setData({
        selectPhoto: true
      })
    }
  },

  onPreViewImage(event) {
    let imgSrc = event.target.dataset.imgsrc;
    wx.previewImage({
      urls: this.data.images,
      current: imgSrc
    })
  },
  // 发布
  send() {

    // 数据存储到云数据中  云数据库 存储， 图片  fileId, OPENID,昵称，头像，时间
    // 图片 -> 云存储  返回 fileId  云文件ID
    if (content.trim() === '') {
      wx.showModal({
        title: "请输入内容",
        content: ''
      })
      return;
    }
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    let promiseArr = [];
    let fileIds = [];
    for (let i = 0; i < this.data.images.length; i++) {
      let p = new Promise((resolve, reject) => {
        let item = this.data.images[i];
        // 获取扩展名
        let suffix = /\.\w+$/.exec(item)[0];
        wx.cloud.uploadFile({
          cloudPath: 'blog/' + Date.now() + '-' + Math.random() * 10000000 + suffix,
          filePath: item,
          success: (res) => {
            console.log(res);
            fileIds = fileIds.concat(res.fileID)
            resolve(res)
          },
          fail: (err) => {
            console.log(err);
            reject()
          }
        })
      })
      promiseArr.push(p);
    }

    // 存入到云数据库中
    Promise.all(promiseArr).then(res => {
      db.collection('blog').add({
        data: {
          ...userInfo,
          content,
          img: fileIds,
          createTime: db.serverDate()
        }
      }).then(res => {
        wx.showToast({
          title: '发布成功',
        })
        wx.hideLoading();
        // 返回blog 并且刷新
        wx.navigateBack();
        const pages = getCurrentPages();
        // 取到上一个界面
        const prevPage = pages[pages.length - 2];
        prevPage.onPullDownRefresh();
      }).catch(err => {
        wx.hideLoading();
        wx.showToast({
          title: '发布失败'
        })
      })
    })


  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})